package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.MqttProducer;
import com.lkd.emq.Topic;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class UserJobMsgHandle implements MsgHandler {
    @Autowired
    private RedisTemplate  redisTemplate;

    @Autowired
    private VMService vmService;
    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
        //接收到售货机发送到协议
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        //定义一个标记
        if (vmStatusContract==null)
        {
            throw new RuntimeException("协议异常");
        }
        //解析数据
        analyticaldata(vmStatusContract);
        //創建工單
       createTask(vmStatusContract.getInnerCode());
    }





    /**
     * 創建工單
     * @param innerCode
     */
    private void createTask(String innerCode) {
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setInnerCode(innerCode);
        taskViewModel.setAssignorId(1);
        taskViewModel.setCreateType(VMSystem.TASK_TYPE_REPAIR);
        //查找員工id
        Integer integer = distributedTask(innerCode);
        taskViewModel.setUserId(integer);
        taskService.add(taskViewModel);
    }



    /**
     * 任務派發
     */
    private Integer distributedTask(String innerCode) {
        //生成日期字符串
        String data = LocalDate.now().plusDays(0).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //查找地區和類型
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        String mKye = "lkd-user-service-redis"+data+vmInfo.getRegionId()+VMSystem.USER_REPAIRER;
        //2.查找員工id
        Set<Object> set = redisTemplate.opsForZSet().range(mKye, 0, 1);
        Integer userId = (Integer)set.stream().collect(Collectors.toList()).get(0);
     return userId;

    }

    /**
     * 解析數據
     * @param vmStatusContract
     */
    private void analyticaldata(VmStatusContract vmStatusContract) {
        int tag = 0;
        List<StatusInfo> statusInfo = vmStatusContract.getStatusInfo();
        if (statusInfo!=null)
        {
            for (StatusInfo info : statusInfo) {
             tag += info.isStatus() ? 1 :0;
            }
        }
    }
}
